<template>
  <div class="book-list">
    <n-card>
      <n-space vertical>
        <n-space justify="space-between">
          <n-space>
            <n-input 
              v-model:value="searchParams.title" 
              placeholder="搜索书名" 
              clearable
              @keyup.enter="handleSearch"
            />
            <n-input 
              v-model:value="searchParams.author" 
              placeholder="搜索作者" 
              clearable
              @keyup.enter="handleSearch"
            />
            <n-select
              v-model:value="searchParams.categoryId"
              :options="categoryOptions"
              placeholder="选择分类"
              clearable
              style="width: 150px;"
            />
            <n-button type="primary" @click="handleSearch">
              <template #icon><SearchOutline /></template>
              搜索
            </n-button>
          </n-space>
          
          <n-button v-if="userStore.isAdmin" type="success" @click="showAddModal = true">
            <template #icon><AddOutline /></template>
            添加图书
          </n-button>
        </n-space>
        
        <n-data-table
          :columns="columns"
          :data="books"
          :loading="loading"
          :pagination="pagination"
          @update:page="handlePageChange"
        />
      </n-space>
    </n-card>
    
    <!-- 添加/编辑图书模态框 -->
    <n-modal v-model:show="showAddModal" preset="card" title="添加图书" style="width: 600px;">
      <n-form ref="formRef" :model="formData" :rules="rules">
        <n-form-item label="ISBN" path="isbn">
          <n-input v-model:value="formData.isbn" placeholder="请输入ISBN" />
        </n-form-item>
        <n-form-item label="书名" path="title">
          <n-input v-model:value="formData.title" placeholder="请输入书名" />
        </n-form-item>
        <n-form-item label="作者" path="author">
          <n-input v-model:value="formData.author" placeholder="请输入作者" />
        </n-form-item>
        <n-form-item label="出版社" path="publisher">
          <n-input v-model:value="formData.publisher" placeholder="请输入出版社" />
        </n-form-item>
        <n-form-item label="分类" path="categoryId">
          <n-select v-model:value="formData.categoryId" :options="categoryOptions" placeholder="选择分类" />
        </n-form-item>
        <n-form-item label="总库存" path="totalStock">
          <n-input-number v-model:value="formData.totalStock" :min="0" placeholder="请输入库存" />
        </n-form-item>
        <n-form-item label="简介" path="description">
          <n-input v-model:value="formData.description" type="textarea" placeholder="请输入简介" />
        </n-form-item>
      </n-form>
      <template #footer>
        <n-space justify="end">
          <n-button @click="showAddModal = false">取消</n-button>
          <n-button type="primary" @click="handleSave">保存</n-button>
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<script setup>
import { ref, h, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { bookApi } from '@/api/book'
import { categoryApi } from '@/api/category'
import { borrowApi } from '@/api/borrow'
import { 
  NCard, NSpace, NInput, NSelect, NButton, NDataTable, NModal, NForm, NFormItem, 
  NInputNumber, NTag, NPopconfirm, useMessage 
} from 'naive-ui'
import { SearchOutline, AddOutline } from '@vicons/ionicons5'

const router = useRouter()
const userStore = useUserStore()
const message = useMessage()

const loading = ref(false)
const books = ref([])
const categoryOptions = ref([])
const showAddModal = ref(false)

const searchParams = ref({
  title: '',
  author: '',
  categoryId: null,
  current: 1,
  size: 10
})

const pagination = ref({
  page: 1,
  pageSize: 10,
  pageCount: 1,
  itemCount: 0
})

const formData = ref({
  isbn: '',
  title: '',
  author: '',
  publisher: '',
  categoryId: null,
  totalStock: 0,
  description: ''
})

const rules = {
  title: { required: true, message: '请输入书名', trigger: 'blur' },
  totalStock: { required: true, type: 'number', message: '请输入库存', trigger: 'blur' }
}

const columns = [
  { title: 'ISBN', key: 'isbn' },
  { title: '书名', key: 'title' },
  { title: '作者', key: 'author' },
  { title: '分类', key: 'categoryName' },
  { 
    title: '库存', 
    key: 'availableStock',
    render: (row) => h(NTag, { 
      type: row.availableStock > 0 ? 'success' : 'error' 
    }, () => `${row.availableStock}/${row.totalStock}`)
  },
  {
    title: '操作',
    key: 'actions',
    render: (row) => h(NSpace, null, () => [
      h(NButton, { 
        size: 'small',
        onClick: () => router.push(`/books/${row.id}`)
      }, () => '详情'),
      row.availableStock > 0 && h(NButton, {
        size: 'small',
        type: 'primary',
        onClick: () => handleBorrow(row.id)
      }, () => '借阅'),
      userStore.isAdmin && h(NButton, {
        size: 'small',
        onClick: () => handleEdit(row)
      }, () => '编辑'),
      userStore.isAdmin && h(NPopconfirm, {
        onPositiveClick: () => handleDelete(row.id)
      }, {
        trigger: () => h(NButton, { size: 'small', type: 'error' }, () => '删除'),
        default: () => '确定删除这本图书吗？'
      })
    ])
  }
]

const loadBooks = async () => {
  loading.value = true
  try {
    const data = await bookApi.getBooks(searchParams.value)
    books.value = data.records
    pagination.value = {
      page: data.current,
      pageSize: data.size,
      pageCount: data.pages,
      itemCount: data.total
    }
  } catch (error) {
    console.error(error)
  } finally {
    loading.value = false
  }
}

const loadCategories = async () => {
  try {
    const data = await categoryApi.getAllCategories()
    categoryOptions.value = data.map(c => ({ label: c.name, value: c.id }))
  } catch (error) {
    console.error(error)
  }
}

const handleSearch = () => {
  searchParams.value.current = 1
  loadBooks()
}

const handlePageChange = (page) => {
  searchParams.value.current = page
  loadBooks()
}

const handleBorrow = async (bookId) => {
  try {
    await borrowApi.borrowBook(bookId)
    message.success('借阅成功')
    loadBooks()
  } catch (error) {
    console.error(error)
  }
}

const handleEdit = (book) => {
  formData.value = { ...book }
  showAddModal.value = true
}

const handleDelete = async (id) => {
  try {
    await bookApi.deleteBook(id)
    message.success('删除成功')
    loadBooks()
  } catch (error) {
    console.error(error)
  }
}

const handleSave = async () => {
  try {
    if (formData.value.id) {
      await bookApi.updateBook(formData.value.id, formData.value)
      message.success('更新成功')
    } else {
      await bookApi.addBook(formData.value)
      message.success('添加成功')
    }
    showAddModal.value = false
    formData.value = { isbn: '', title: '', author: '', publisher: '', categoryId: null, totalStock: 0, description: '' }
    loadBooks()
  } catch (error) {
    console.error(error)
  }
}

onMounted(() => {
  loadBooks()
  loadCategories()
})
</script>

